package com.sky.service.impl;


import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.User;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
   private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 营业额统计接口
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistic(LocalDate begin, LocalDate end) {
        List<Double> turnoverList = new ArrayList<>();  //当日营业额

        //遍历日期，获取日期参数以及当日营业额统计情况
        //日期参数获取
        List<LocalDate> dateList = dateList(begin, end);   //日期参数（x轴）
        //营业额参数获取
        for (LocalDate now : dateList) {
            //获取当日的起始时间与结束时间的具体时分秒
            LocalDateTime beginTime = LocalDateTime.of(now, LocalTime.MIN); //获取当日零点
            LocalDateTime endTime = LocalDateTime.of(now, LocalTime.MAX); //获取当日23：59：59

            //封装一下，再查询数据库
            Map params = new HashMap<>();
            params.put("begin", beginTime);
            params.put("end", endTime);
            params.put("status", Orders.COMPLETED); //已完成订单才能查询！
            Double turnover = orderMapper.sumByMap(params);
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }

        TurnoverReportVO turnoverReportVO = TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))   //lang包下的！
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();

        return turnoverReportVO;
    }


    /**
     * 用户统计接口
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistic(LocalDate begin, LocalDate end) {
        List<LocalDate> dates = dateList(begin, end);
        List<Integer> totalUserList = new ArrayList<>(); //当天的全部用户
        List<Integer> newUserList = new ArrayList<>();   //当天的新用户


        //为每一天计算用户总数
        for (LocalDate today : dates) {
            //获取当天时间段（00:00:000~23:59:59)
            LocalDateTime beginTime = LocalDateTime.of(today, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(today, LocalTime.MAX);

            //查询全部用户（从begin截至到today）
            //封装查询参数
            Map params = new HashMap<>();
            params.put("endTime", endTime);
            Integer totalUser = userMapper.countMap(params); //仅通过当日结束时间来查询全部用户
            totalUserList.add(totalUser == null ? 0 : totalUser);

            //查询新用户（当天）
            params.put("beginTime", beginTime);
            Integer newUser = userMapper.countMap(params);   //通过当日起始与结束时间来查询全部用户
            newUserList.add(newUser == null ? 0 : newUser);
        }

        UserReportVO userReportVO = UserReportVO.builder()
                .dateList(StringUtils.join(dates, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .build();

        return userReportVO;
    }


    /**
     * 订单统计接口
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO ordersStatistic(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = dateList(begin, end);    //获取日期列表
        List<Integer> orderCountList = new ArrayList<>();    //每日订单数列表
        List<Integer> validOrderCountList = new ArrayList<>();   //每日有效订单数列表
        Integer totalOrderCount = 0;    //订单总数
        Integer validOrderCount = 0;    //有效订单总数

        //获取每日订单，然后再进行总数统计
        for (LocalDate today : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(today, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(today, LocalTime.MAX);

            Map params = new HashMap<>();

            //首先查询每日订单总数，即直接以时间段查询
            params.put("begin", beginTime);
            params.put("end", endTime);
            Integer orderCount = orderMapper.countByMap(params);    //当天订单总数
            orderCount = orderCount == null ? 0 : orderCount;
            //将当天订单总数加入到集合中
            orderCountList.add(orderCount);
            //订单总数的叠加
            totalOrderCount += orderCount;

            //然后通过订单状态获取有效订单
            params.put("status", Orders.COMPLETED);
            Integer validOrderCountToday = orderMapper.countByMap(params);  //当天有效订单数
            validOrderCountToday = validOrderCountToday == null ? 0 : validOrderCountToday;
            //将当天有效订单数加入集合中
            validOrderCountList.add(validOrderCountToday);
            //有效订单数的叠加
            validOrderCount += validOrderCountToday;
        }

        //订单完成率
        Double orderCompletionRate = totalOrderCount == 0 ? 0 : (double)validOrderCount / totalOrderCount;    //注意java的除法运算哇！！

        //参数封装
        OrderReportVO orderReportVO = OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();

        return orderReportVO;
    }


    /**
     * 查询销售量排名top10
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = dateList(begin, end);    //日期列表

        //无需显示当日，直接显示当前时间段的统计结果即可
        //获取排名前十的商品的DTO集合（包含name、number）
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> goodsSalesList = orderMapper.top10ByTime(beginTime, endTime);

        //通过stream流，遍历并且赋值集合
        List<String> nameList = goodsSalesList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numberList = goodsSalesList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        SalesTop10ReportVO salesTop10ReportVO = SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();

        return salesTop10ReportVO;
    }


    /**
     * 导出运营数据报表
     * @param response
     */
    @Override
    public void exportBussisnessData(HttpServletResponse response) throws IOException {
        /*
        查询数据库，获取营业数据——近30天
         */
        //获取时间段（起始天的00:00:00——昨天的23:59:59）
        LocalDate start = LocalDate.now().minusDays(30);    //30天前
        LocalDateTime startTime = LocalDateTime.of(start, LocalTime.MIN);
        LocalDate end = LocalDate.now().minusDays(1);  //查询昨天
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        //查询概览数据
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(startTime, endTime);

        /*
        通过POI将营业数据写入excel中
         */
        //根据已有模板创建excel文件（将已有模板通过输入流写入当前新建文件中）
        //创建一个输入流，获取运营数据报表模板文件
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            //根据输入流创建excel文件
            XSSFWorkbook excel = new XSSFWorkbook(in);

            /*
            填充数据
            */
            //获取标签页
            XSSFSheet sheet = excel.getSheet("sheet1");

            //概览数据
            //填充时间（第二行第二格）
            sheet.getRow(1).getCell(1).setCellValue("时间：" + start + "——" + end);
            //填充营业额（第四行第三格）
            sheet.getRow(3).getCell(2).setCellValue(businessDataVO.getTurnover());
            //填充订单完成率（第四行第五格）
            sheet.getRow(3).getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            //填充新增用户数（第四行第七格）
            sheet.getRow(3).getCell(6).setCellValue(businessDataVO.getNewUsers());
            //填充有效订单（第五行第三格）
            sheet.getRow(4).getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            //填充平均客单价(第五行第五格）
            sheet.getRow(4).getCell(4).setCellValue(businessDataVO.getUnitPrice());

            //明细数据
            //按照三十天每一天的数据进行遍历添加即可（从第八行开始）
            LocalDate today = start;
            int nowRowNumber = 7;
            while (!today.equals(end)){
                LocalDateTime todayStart = LocalDateTime.of(today, LocalTime.MIN);
                LocalDateTime todayEnd = LocalDateTime.of(today, LocalTime.MAX);
                //获取当日数据
                BusinessDataVO todayData = workspaceService.getBusinessData(todayStart, todayEnd);

                //填充数据
                //获取当前行
                XSSFRow row = sheet.getRow(nowRowNumber);
                //填充日期（第二格）
                row.getCell(1).setCellValue("" + today);
                //填充营业额（第三格）
                row.getCell(2).setCellValue(todayData.getTurnover());
                //填充有效订单（第四格）
                row.getCell(3).setCellValue(todayData.getValidOrderCount());
                //填充订单完成率（第五格）
                row.getCell(4).setCellValue(todayData.getOrderCompletionRate());
                //填充平均客单价（第六格）
                row.getCell(5).setCellValue(todayData.getUnitPrice());
                //填充新增用户（第七格）
                row.getCell(6).setCellValue(todayData.getNewUsers());

                //变量自增
                today = today.plusDays(1);
                nowRowNumber += 1;
            }

            //通过输出流将excel写入到客户端浏览器（即下载）
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //关闭资源
            out.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 生成日期列表
     * @param begin
     * @param end
     * @return
     */
    private List<LocalDate> dateList(LocalDate begin, LocalDate end){
        List<LocalDate> dateList = new ArrayList<>();
        LocalDate time = begin; //追踪变量
        while (!time.equals(end)){
            dateList.add(time);
            time = time.plusDays(1);
        }
        dateList.add(time);

        return dateList;
    }
}
